/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { View, Text, Image, StatusBar } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { Input } from 'react-native-elements';
import { pxToDp } from '../../../utils/stylesKits';
import validator from '../../../utils/validator';
import request from '../../../utils/request';
import { ACCOUNT_LOGIN, ACCOUNT_VALIDATEVCODE } from '../../../utils/pathMap';
import THButton from '../../../components/THButton';
import CodeBox from '../../../components/CodeBox';
import * as protogenesisToast from '@ant-design/react-native';

class Login extends Component {
    state = {
        phoneNumber: "17344995555", // 手机号码
        phoneValid: true,// 手机号码是否合法
        showLogin: true, // 是否显示登录页面
        btnText: '重新获取',// 获取验证码的文本
        isCountItme: false,// 用于节流 当倒计时开启时不会再开启倒计时
    }
    // 登录框手机输入
    phoneNumberChangeText = (e) => {
        this.setState({
            phoneNumber: e, // 手机号码
            phoneValid: true, // 手机号码是否合法
        });
    }
    // 手机号码点击完成时的触发
    phoneNumberSubmitEditing = async () => {
        /**
         * 对手机号码进行校验
         * 通过校验并且获取到验证码后切换到登录界面
         */
        const { phoneNumber } = this.state;
        if (!validator.validatePhone(phoneNumber)) {
            // 没有通过
            this.setState({
                phoneValid: false,
            });
            return;
        }
        // 获取验证码
        const res = await request.post(ACCOUNT_LOGIN, { phone: phoneNumber });
        const { code = '401' } = res;
        if (code === '10000') {
            // 请求成功
            this.setState({
                showLogin: false,
            });
            // 开启定时器不让用户再次点击发送验证码
            this.countDown(5);
        } else {
            // 请求失败
            this.setState({
                showLogin: true,
            });
        }
    }
    // 点击获取验证码
    handleGetCode = () => {
        this.phoneNumberSubmitEditing();
    }
    // 开启获取验证码的定时器
    countDown = (seconds) => {
        const { isCountItme } = this.state;
        // 倒计时是否已经开启
        if (isCountItme) {
            return
        }
        this.setState({
            btnText: `重新获取(${seconds}s)`,
            isCountItme: true
        });
        console.log(seconds);
        let timer = setInterval(() => {
            seconds--;
            this.setState({
                btnText: `重新获取(${seconds}s)`,
            });
            if (seconds <= 0) {
                clearInterval(timer);
                this.setState({
                    btnText: '重新获取',
                    isCountItme: false,
                });
            }
        }, 1000);
    }

    // 重新获取验证码
    repGetvcode = () => {
        this.countDown(5);
    }

    // 当密码框输入完成后
    onvcodeKeyPress = async (e, value) => {
        /**
         * @handler 
         * 1. 对验证码做校验
         * 2. 将手机号码和验证码 一起发送给后台
         * 3. 返回值isNew状态
         *   1). 如果isNew为true 就是新用户-->完善个人信息页面
         *   2). 否则就是老用户--> 交友 --> 首页
         */
        const { phoneNumber } = this.state;
        const newValue = e.nativeEvent.key + value
        if (value.length !== 5 ) return;
        const res = await request.post(ACCOUNT_VALIDATEVCODE, { phone: phoneNumber, vcode: newValue });
        const { code='10001',data,msg } = res;
        if(code!=='10000'){
            protogenesisToast.Toast.fail(msg, 1);
            return;
        }
        if(data.isNew){
            // 新用户 跳转到用户信息完善页面
            this.props.navigation.navigate("UserInfo");
        }else{
            // 老用户
            alert('老用户');
        }
    }

    // 当软键盘的确定/提交按钮被按下的时
    onvcodeSubmitEditing = async (e, value) => {
        if (value.length !== 6) {
            protogenesisToast.Toast.fail('验证码格式不正确', 1);
            return
        }
    }

    // 登录布局
    loginDom = () => {
        const { phoneNumber, phoneValid, btnText } = this.state;
        return (
            <View>
                <View>
                    <Text style={{ fontSize: pxToDp(25), color: "#888", fontWeight: "bold" }}>手机号登陆注册</Text>
                    {/* 
                  * 在react-native 里使用别人组件的icon需要额外的配置 
                  * keyboardType = phone-pad 当input框获取焦点时弹出数字输入框
                  * errorMessage 出现错误时的提示
                  * onSubmitEditing 输入完成后触发
                 */}
                    <View style={{ marginTop: pxToDp(30) }}>
                        <Input
                            placeholder='请输入手机号码'
                            leftIcon={{ type: 'font-awesome', name: 'phone', color: "#ccc", size: pxToDp(20) }}
                            maxLength={11}
                            value={phoneNumber}
                            inputStyle={{ color: "#333" }}
                            onChangeText={this.phoneNumberChangeText}
                            errorMessage={!phoneValid ? "手机号码格式错误" : null}
                            onSubmitEditing={this.phoneNumberSubmitEditing}
                            keyboardType="phone-pad"
                        />
                    </View>
                    {/* 渐变按钮 */}
                    <View style={{ width: '85%', height: pxToDp(45), alignSelf: 'center' }}>
                        <THButton style={{ borderRadius: pxToDp(20) }} onPress={this.handleGetCode}>{btnText}</THButton>
                    </View>
                </View>
            </View>
        )
    }

    //注册布局
    registered = () => {
        const { phoneNumber, btnText, isCountItme } = this.state;
        return (
            <View>
                <View><Text style={{ color: '#666', fontSize: pxToDp(25), fontWeight: 'bold' }}>输入6位验证码</Text></View>
                <View><Text style={{ marginTop: pxToDp(12), marginBottom: pxToDp(10), fontSize: pxToDp(20), color: '#999' }}>已发送到:+{phoneNumber}</Text></View>
                {/* 验证码输入框 */}
                <View><CodeBox onvcodeKeyPress={this.onvcodeKeyPress} onvcodeSubmitEditing={this.onvcodeSubmitEditing} /></View>
                {/* 渐变按钮 */}
                <View style={{ width: '85%', height: pxToDp(45), alignSelf: 'center', marginTop: pxToDp(60) }}>
                    <THButton disabled={isCountItme} onPress={() => this.repGetvcode()} style={{ borderRadius: pxToDp(20) }}>{btnText}</THButton>
                </View>
            </View>
        );
    }

    render() {
        const { showLogin } = this.state;
        return (
            <View>
                {/*
             * 手机状态栏开始 
             * backgroundColor是手机状态栏的背景色 
             * translucent的意思是app背景覆盖状态栏
             */}
                <StatusBar backgroundColor="transparent" translucent={true} />
                {/* 手机状态栏结束 */}
                {/* 
              * 登录背景图开始
              * 高度的200是dp单位不是px
             */}
                <Image style={{ width: '100%', height: pxToDp(200) }} source={require('../../../res/profileBackground.jpg')} />
                {/* 登录背景图结束 */}
                {/* 内容部分开始 */}
                <View style={{ padding: pxToDp(20) }}>
                    {showLogin ? this.loginDom() : this.registered()}
                </View>
                {/* 内容部分结束 */}
            </View>
        );
    }
}
export default Login;
